﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DataAccess.DataModel;
using DataAccess.DataAccess;

namespace ClientAdminServer
{
    public partial class UserForm : Form
    {
        internal int UserIdModified = -1;

        public UserForm()
        {
            InitializeComponent();
            LoadUserData();
            LoadTripData();
        }


        private void LoadTripData()
        {
            DataAccessClass dataAccessClass = new DataAccessClass();
            List<UsersTrips> usersTripses = dataAccessClass.ObtenerViajesUsuarios();
            DataTable table = new DataTable("UsersTrips");
            DataColumn userIdColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.Int32"),
                ColumnName = "UserId"
            };
            table.Columns.Add(userIdColumn);
            DataColumn userNameColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.String"),
                ColumnName = "UserName"
            };
            table.Columns.Add(userNameColumn);
            DataColumn userAvailableAmountColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.Decimal"),
                ColumnName = "AvailableAmount"
            };
            table.Columns.Add(userAvailableAmountColumn);
            DataColumn userKmColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.Decimal"),
                ColumnName = "UserKm"
            };
            table.Columns.Add(userKmColumn);
            DataColumn userAmountColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.Decimal"),
                ColumnName = "UserAmountSpend"
            };
            table.Columns.Add(userAmountColumn);

            DataRow row;
            foreach (UsersTrips usersTrips in usersTripses)
            {
                row = table.NewRow();
                row["UserId"] = usersTrips.UserId;
                row["UserName"] = usersTrips.UserName;
                row["AvailableAmount"] = usersTrips.UserAmount;
                row["UserKm"] = usersTrips.UserKm;
                row["UserAmountSpend"] = usersTrips.UserAmountSpend;
                table.Rows.Add(row);
            }
            dataGridViewTrips.DataSource = table.DefaultView;

        }

        private void LoadUserData()
        {
            btnCancel.Visible = false;
            btnDelete.Visible = true;
            btnNew.Visible = true;
            btnSave.Visible = true;

            DataAccessClass dataAccessClass = new DataAccessClass();
            List<User> usuarios = dataAccessClass.ObtenerUsuarios();
            DataTable table = new DataTable("Users");
            DataColumn userIdColumn = new DataColumn
                                          {
                                              DataType = System.Type.GetType("System.Int32"),
                                              ColumnName = "UserId"
                                          };
            table.Columns.Add(userIdColumn);
            DataColumn userNameColumn = new DataColumn
                                            {
                                                DataType = System.Type.GetType("System.String"),
                                                ColumnName = "UserName"
                                            };
            table.Columns.Add(userNameColumn);
            DataColumn userPasswordColumn = new DataColumn
                                                {
                                                    DataType = System.Type.GetType("System.String"),
                                                    ColumnName = "UserPassword"
                                                };
            table.Columns.Add(userPasswordColumn);
            DataColumn isActiveColumn = new DataColumn
                                            {
                                                DataType = System.Type.GetType("System.Boolean"),
                                                ColumnName = "Activo"
                                            };
            table.Columns.Add(isActiveColumn);
            DataColumn isPrePayColumn = new DataColumn
                                            {
                                                DataType = System.Type.GetType("System.Boolean"),
                                                ColumnName = "Prepago"
                                            };
            table.Columns.Add(isPrePayColumn);
            DataColumn amountPrePayColumn = new DataColumn
                                                {
                                                    DataType = System.Type.GetType("System.Decimal"),
                                                    ColumnName = "SaldoPrepago"
                                                };
            table.Columns.Add(amountPrePayColumn);

            DataRow row;
            foreach (User usuario in usuarios)
            {
                row = table.NewRow();
                row["UserId"] = usuario.UserId;
                row["UserName"] = usuario.UserName;
                row["UserPassword"] = usuario.UserPassword;
                row["Activo"] = usuario.Activo;
                row["Prepago"] = usuario.Prepago;
                row["SaldoPrepago"] = usuario.SaldoPrepago;
                table.Rows.Add(row);
            }
            dataGridViewClients.DataSource = table.DefaultView;
            //dataGridViewClients.Columns["UserId"].ReadOnly = true;
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if ((txtBoxUserName.Text != null || txtBoxUserName.Text != "") && 
                (txtBoxPassword.Text != null || txtBoxPassword.Text != "") &&
                (txtBoxAmount.Text != null || txtBoxAmount.Text != ""))
            {
                var userName = txtBoxUserName.Text.Trim();
                var password = txtBoxPassword.Text.Trim();
                var isActive = chckBoxActive.Checked;
                var isPrepaid = chckBoxPrepaid.Checked;
                decimal amount = 0;
                if (isPrepaid)
                    amount = Convert.ToDecimal(txtBoxAmount.Text.Trim());
                DataAccessClass dataAccessClass = new DataAccessClass();
                if (UserIdModified > 0)
                {
                    var ok = dataAccessClass.ModificarUsuario(UserIdModified, userName, password, isActive, isPrepaid,
                                                              amount);
                    if (ok)
                    {
                        dataGridViewClients.DataSource = null;
                        LoadUserData();
                    }
                    else
                    {
                        MessageBox.Show(@"You can't update this user with that information.", @"Update errpr", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                    }
                }
                else
                {
                    var ok = dataAccessClass.CrearUsuario(userName, password, isPrepaid, amount);
                    if (ok)
                    {
                        dataGridViewClients.DataSource = null;
                        LoadUserData();
                    }
                    else
                    {
                        MessageBox.Show(@"You can't update this user with that information.", @"Update error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show(@"You must fill all data in the form.", @"Validate error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }

        }

        private void dataGridViewClients_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            btnCancel.Visible = true;
            btnDelete.Visible = true;
            btnNew.Visible = true;
            btnSave.Visible = true;

            int i;
            i = e.RowIndex;
            UserIdModified = (int) dataGridViewClients.Rows[i].Cells[0].Value;
            txtBoxUserName.Text = (string) dataGridViewClients.Rows[i].Cells[1].Value;
            txtBoxPassword.Text = (string) dataGridViewClients.Rows[i].Cells[2].Value;
            chckBoxActive.Checked = (bool)dataGridViewClients.Rows[i].Cells[3].Value;
            chckBoxPrepaid.Checked = (bool)dataGridViewClients.Rows[i].Cells[4].Value;
            txtBoxAmount.Text = dataGridViewClients.Rows[i].Cells[5].Value.ToString();
            btnNew.Visible = false;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            btnCancel.Visible = true;
            btnDelete.Visible = false;
            btnNew.Visible = false;
            btnSave.Visible = true;

            CleanScreen();
        }

        private void CleanScreen()
        {
            UserIdModified = -1;
            txtBoxUserName.Text = "";
            txtBoxPassword.Text = "";
            chckBoxActive.Checked = true;
            chckBoxPrepaid.Checked = true;
            txtBoxAmount.Text = @"0";
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnCancel.Visible = false;
            btnDelete.Visible = true;
            btnNew.Visible = true;
            btnSave.Visible = true;

            CleanScreen();
        }

        private void chckBoxPrepaid_CheckedChanged(object sender, EventArgs e)
        {
            if (!chckBoxPrepaid.Checked)
            {
                txtBoxAmount.Text = @"0";
                txtBoxAmount.ReadOnly = true;
            }
            else
            {
                txtBoxAmount.ReadOnly = false;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DataAccessClass dataAccessClass = new DataAccessClass();
            if (UserIdModified > 0)
            {
                var ok = dataAccessClass.EliminarUsuario(UserIdModified);
                if (ok)
                {
                    dataGridViewClients.DataSource = null;
                    LoadUserData();
                }
                else
                {
                    MessageBox.Show(@"You can't delete this user, verify with server admin.", @"Delete error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dataGridViewTrips.SelectedRows.Count ==1)
            {
                int userid = (int) dataGridViewTrips.SelectedRows[0].Cells[0].Value;
                LoadUserTripData(userid);

            }
        }

        private void LoadUserTripData(int userid)
        {
            DataAccessClass dataAccessClass = new DataAccessClass();
            List<Trip> userTrips = dataAccessClass.ObtenerViajesUsuario(userid);

            DataTable table = new DataTable("UserTrips");
            DataColumn tripIdColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.Int32"),
                ColumnName = "TripId"
            };
            table.Columns.Add(tripIdColumn);
            DataColumn tripKmColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.String"),
                ColumnName = "Kilometers"
            };
            table.Columns.Add(tripKmColumn);
            DataColumn tripCostColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.Decimal"),
                ColumnName = "TripCost"
            };
            table.Columns.Add(tripCostColumn);
            DataColumn tripStateColumn = new DataColumn
            {
                DataType = System.Type.GetType("System.String"),
                ColumnName = "TripState"
            };
            table.Columns.Add(tripStateColumn);
            DataRow row;
            foreach (Trip userTrip in userTrips)
            {
                row = table.NewRow();
                row["TripId"] = userTrip.ViajeId;
                row["Kilometers"] = userTrip.Kilometraje;
                row["TripCost"] = userTrip.CostoViaje;
                switch (userTrip.Estado)
                {
                    case 1:
                        row["TripState"] = "NEW";
                        break;
                    case 2:
                        row["TripState"] = "ON COURSE";
                        break;
                    case 3:
                        row["TripState"] = "FINISHED";
                        break;
                }
                table.Rows.Add(row);
            }
            dataGridViewTripsDetail.DataSource = table.DefaultView;

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadTripData();
        }

        private void btnRefreshUsers_Click(object sender, EventArgs e)
        {
            LoadUserData();
        }

    }
}
